<template>
  <div class="flex items-center justify-center px-2.5 md:px-6 bg-[#fff]">
    <div class="w-full max-w-xl text-center mt-4 mb-12">
      <!-- 文字 -->
      <div class="mb-14">
        <div class="md:mt-24 mb-10 block text-xl font-bold">OKPAN.COM</div>
        <div class="mb-0.5 text-3xl font-extrabold md:text-4xl">
          {{ i18nStore.translate('welcome_to_FileQX') }}
        </div>
        <div class="text-xl font-normal md:text-2xl">
          {{ i18nStore.translate('please_enter_your_phone_or_email_to_login') }}
        </div>
      </div>
      <!-- 表单 -->
      <div class="mb-14">
        <div class="mb-3">
          <div class="md:flex justify-center items-center mb-2">
            <div class="w-[100px] font-bold mr-4 md:text-right text-left mb-1">
              {{ i18nStore.translate('account') }}
            </div>
            <input
              type="text"
              v-model="emailAndPhone"
              v-bind="emailAndPhoneAttrs"
              :placeholder="i18nStore.translate('please_enter_email_or_phone')"
              class="md:w-[330px] w-[100%] px-5 py-2.5 font-bold rounded-lg border-0 focus:outline-theme-color text-lg bg-[#f4f5f6]"
            />
          </div>
          <div class="flex md:pl-[180px] text-xs text-red-600">
            {{ errors.emailAndPhone }}
          </div>
        </div>
        <div class="mb-12">
          <div class="md:flex justify-center items-center mb-2">
            <div class="w-[100px] font-bold mr-4 md:text-right text-left mb-1">
              {{ i18nStore.translate('password') }}
            </div>
            <input
              type="password"
              v-model="password"
              v-bind="passwordAttrs"
              :placeholder="i18nStore.translate('please_enter_password')"
              class="md:w-[330px] w-[100%] px-5 py-2.5 font-bold rounded-lg border-0 focus:outline-theme-color text-lg bg-[#f4f5f6]"
            />
          </div>
          <div class="flex md:pl-[180px] text-xs text-red-600">
            {{ errors.password }}
          </div>
        </div>
        <!-- tips -->
        <div class="flex justify-center items-center mb-6">
          <div
            class="w-[152px] flex justify-center items-center rounded-lg border-2 border-black px-3.5 py-1.5 cursor-pointer"
            @click="login"
          >
            <myButton class="mr-1 text-lg font-extrabold">
              {{ i18nStore.translate('login') }}
            </myButton>
            <svg
              data-v-0249f6ea=""
              xmlns="http://www.w3.org/2000/svg"
              width="20px"
              height="20px"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              class="vue-feather text-theme-color -mr-1 feather feather-chevron-right"
            >
              <polyline data-v-0249f6ea="" points="9 18 15 12 9 6"></polyline>
            </svg>
          </div>
        </div>
        <div>
          <span>{{ i18nStore.translate('no_account') }} </span>
          <span class="font-bold text-theme-color cursor-pointer">
            <router-link to="/register"
              >{{ i18nStore.translate('sign_up_now') }}
            </router-link></span
          >
          <span> or </span>
          <span>{{ i18nStore.translate('forget_password') }} </span>
          <span class="font-bold text-theme-color cursor-pointer">
            <router-link to="/resetPassword"
              >{{ i18nStore.translate('Reset') }}
            </router-link></span
          >
        </div>
      </div>
      <div
        class="flex items-center justify-center cursor-pointer"
        @click="toWechatLogin"
        v-if="!isMobileDevice()"
      >
        <img src="@/assets/login/wechatIcon.png" class="w-8 h-8 mr-4" />
        <span> {{ i18nStore.translate('wechat_scan_login') }} </span>
      </div>
    </div>
    <!-- toast -->
    <Toast position="center" group="loginResult" />
  </div>
</template>
<script setup>
import { useRouter } from 'vue-router';
import Toast from 'primevue/toast';
import { useForm } from 'vee-validate';
import { useToast } from 'primevue/usetoast';
import { useI18nStore, useUserInfoStore } from '@/stores/index.js';
import { loginApi, getWechatQrCodeApi } from '@/apis/user.js';
const i18nStore = useI18nStore();
const router = useRouter();
const userInfoStore = useUserInfoStore();
const { userInfo, okCloudDiskToken, tokenTimeStamp, userId } =
  storeToRefs(userInfoStore); // 用户信息
const toast = useToast();
// 校验规则
const emailReg = (value) => {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
};
const phoneReg = (value) => {
  return /^1[3-9]\d{9}$/.test(value);
};
function isMobileDevice() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  );
}
// 表单生成器
const { values, errors, defineField, meta } = useForm({
  validationSchema: {
    emailAndPhone: (val) =>
      emailReg(val) || phoneReg(val)
        ? true
        : i18nStore.translate('please_enter_a_valid_email_or_phone_number'),
    password: (val) => true
  }
});
// 表单字段
const [emailAndPhone, emailAndPhoneAttrs] = defineField('emailAndPhone');
const [password, passwordAttrs] = defineField('password');

// 登录
const isPasswordError = ref(false);
const login = async () => {
  if (!meta.value.valid) {
    return;
  }
  let res;
  const formData = new FormData();
  formData.append('account', emailAndPhone.value);
  formData.append('password', password.value);
  res = await loginApi(formData);
  if (res.code === 0) {
    toast.add({
      severity: 'success',
      summary: i18nStore.translate('login_success'),
      detail: '',
      group: 'loginResult',
      life: 1500
    });
    userInfo.value = res.data.user;
    okCloudDiskToken.value = res.data.accessToken;
    userId.value = res.data.userId;
    tokenTimeStamp.value = Date.now();
    setTimeout(() => {
      router.back();
    }, 1000);
  } else {
    toast.add({
      severity: 'error',
      summary: res.message,
      detail: '',
      group: 'loginResult',
      life: 1500
    });
  }
};
// 微信扫码登录
const toWechatLogin = async () => {
  const res = await getWechatQrCodeApi({
    redirectUri: 'https://okpan.com',
    type: 32
  });
  window.location.href = res.data;
};
</script>
<style lang="scss" scoped></style>
